﻿using System;
using System.Collections.Generic;
using StockholmsStad.Runtime.Serialization.DataContract;
using StockholmsStad.Windows.UI.Modules.Couple.Interfaces;
using StockholmsStad.Windows.UI.Modules.Couple.Models;
using System.Windows.Controls;
using StockholmsStad.Runtime.Serialization.DataContract.Enums;
using StockholmsStad.Windows.UI.Modules.Couple.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;
using System.Windows.Input;
using System.Windows;

namespace StockholmsStad.Windows.UI.Modules.Couple.Views
{
    /// <summary>
    /// Interaction logic for TabItemBookingView.xaml
    /// </summary>
    public partial class TabItemBookingView : IBookingView
    {
        private int loadedTicketId;
        private CeremonyType loadedCeremonyType;
        private bool isInContextChangeMode;
        private List<ValueIdPair> ceremonyTypes;
        private readonly IBookingService bookingService;
        private readonly ICeremonyService ceremonyService;
        private readonly ICouplesController couplesController;

        private readonly SubscriptionToken subscriptionToken;
        private readonly IEventAggregator eventAggregator;

        public TabItemBookingView(IBookingService bookingService, ICouplesController controller,
            ICeremonyService ceremonyService, IEventAggregator aggregator)
        {
            this.bookingService = bookingService;
            this.ceremonyService = ceremonyService;
            couplesController = controller;
            eventAggregator = aggregator;

            Initialized += TabItemBookingView_Initialized;
            
            InitializeComponent();

            Loaded += TabItemBookingView_Loaded;
            DataContextChanged += TabItemBookingView_DataContextChanged;

            var addedBookingEvent = eventAggregator.GetEvent<BookingAddedEvent>();
            var canceledBookingEvent = eventAggregator.GetEvent<BookingCancelledEvent>();

            if (subscriptionToken != null)
            {
                addedBookingEvent.Unsubscribe(subscriptionToken);
                canceledBookingEvent.Unsubscribe(subscriptionToken);
            }

            subscriptionToken = addedBookingEvent.Subscribe(BookingAddedEventHandler, ThreadOption.UIThread, false);
            subscriptionToken = canceledBookingEvent.Subscribe(BookingCancelledEventHandler, ThreadOption.UIThread, false);

            PreviewLostKeyboardFocus += TabItemBookingView_PreviewLostKeyboardFocus;

        }

        private void TabItemBookingView_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var newfocus = e.NewFocus;
            if (newfocus.GetType() == typeof(TabItem))
            {
                var tabItem = (TabItem)newfocus;
                if (!tabItem.Header.ToString().Equals(HeaderNames.Booking))
                {
                    //Specialfall då vi har två andra tabbar på sidan
                    if (!tabItem.Header.ToString().Equals("Närmast") && !tabItem.Header.ToString().Equals("Alla"))
                    {
                        //Byte till annan tab
                        e.Handled = HandleChange();
                    }
                }
            }
        }

        private bool HandleChange()
        {
            if (Model.IsInChangeMode)
            {
                var result = MessageBox.Show(Properties.Resources.UnsavedChanges, "Information", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                if (result == MessageBoxResult.Yes)
                {
                    //ToggleMode(false);
                }
                else
                {
                    return true;
                }
            }
            return false;
        }


        private void BookingCancelledEventHandler(BookingPresentationModel obj)
        {
        }

        private void BookingAddedEventHandler(BookingPresentationModel obj)
        {
        }

        #region IBookingView Members

        public BookingPresentationModel Model
        {
            get { return DataContext as BookingPresentationModel; }
            set { DataContext = value; }
        }

        private int selectedTicketId;
        public int SelectedTicketId
        {
            get { return selectedTicketId; }
            set
            {
                selectedTicketId = value;
                if (IsLoaded && loadedTicketId != SelectedTicketId)
                {
                    Model = bookingService.GetBooking(selectedTicketId);
                    loadedTicketId = selectedTicketId;
                    loadedCeremonyType = Model.CeremonyType;
                    //couplesController.SetSelectedBooking(Model);
                }
            }
        }

        #endregion

        private void TabItemBookingView_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            var model = DataContext as BookingPresentationModel;

            if(model != null)
            {
                isInContextChangeMode = true;

                if (ceremonyTypes != null && ceremonyTypes.Count > 0)
                    rbListCeremonyTypes.SelectedIndex = FindSelectedItem(model.CeremonyType);

                couplesController.SetSelectedBooking(Model);

                isInContextChangeMode = false;
            }
        }

        private void TabItemBookingView_Initialized(object sender, EventArgs e)
        {

            ceremonyTypes = ceremonyService.GetCeremonyTypes();
            rbListCeremonyTypes.ItemsSource = ceremonyTypes;

            // We need to initialize in order to set the tab name properly
            Model = bookingService.GetBooking(loadedTicketId);
        }

        private void TabItemBookingView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (loadedTicketId != SelectedTicketId)
            {
                Model = bookingService.GetBooking(selectedTicketId);
                loadedTicketId = selectedTicketId;
            }

            if(ceremonyTypes != null && ceremonyTypes.Count > 0)
                rbListCeremonyTypes.SelectedIndex = FindSelectedItem(Model.CeremonyType);

            couplesController.SetSelectedBooking(Model);
        }

        private int FindSelectedItem(CeremonyType ceremonyType)
        {
            for(int i = 0; i < rbListCeremonyTypes.Items.Count; i++)
            {
                var item = (ValueIdPair)rbListCeremonyTypes.Items[i];
                if(item.Name == Enum.GetName(typeof(CeremonyType), ceremonyType))
                    return i;
            }

            return -1;
        }

        private void rbListCeremonyTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(e.AddedItems != null && e.AddedItems[0] != null)
            {
                var ceremonyType = (ValueIdPair)e.AddedItems[0];

                Model.CeremonyType = (CeremonyType)Enum.Parse(typeof(CeremonyType), ceremonyType.Name);

                if (!isInContextChangeMode)
                {
                    //Om man redan har en bokning och har bytt ceremonityp och sen bytt tillbaka
                    //så laddar vi om bokningen
                    if(loadedCeremonyType == Model.CeremonyType)
                    {
                        Model = bookingService.GetBooking(loadedTicketId);
                    }
                    //Om man redan har en bokning och byter ceremonityp så skapar vi en nytt bokningsobjekt
                    //för att rensa bort en del information så att ombokningen fungerar
                    else
                    {
                        var copiedBooking = bookingService.CopyBooking(Model);
                        Model = copiedBooking;
                    }
                }
                couplesController.SetSelectedBooking(Model);
            }

        }
    }
}
